<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

    <title>Horizontal Playground</title>

    <script src="../blockly_uncompressed_horizontal.js"></script>
    <script src="../msg/messages.js"></script>
    <script src="../blocks/math.js"></script>
    <script src="../blocks/text.js"></script>
    <script src="../blocks_horizontal/control.js"></script>
    <script src="../blocks_horizontal/event.js"></script>
    <script src="../blocks_horizontal/wedo.js"></script>
    <script>
      'use strict';

      // Depending on the URL argument, render as LTR or RTL.
      var rtl = (document.location.search == '?rtl');
      var workspace = null;

      function start() {
        // Restore sounds state.
        var soundsEnabled = sessionStorage.getItem('soundsEnabled');
        if (soundsEnabled === null) {
          soundsEnabled = true;
        } else {
          soundsEnabled = (soundsEnabled === 'true');
        }
        setSoundsEnabled(soundsEnabled);

        // Setup blocks
        var toolbox = document.getElementById('toolbox');
        workspace = Blockly.inject('blocklyDiv', {
          comments: false,
          disable: false,
          collapse: false,
          maxBlocks: Infinity,
          media: '../media/',
          readOnly: false,
          rtl: rtl,
          scrollbars: true,
          toolbox: toolbox,
          trashcan: true,
          horizontalLayout: true,
          toolboxPosition: 'start',
          sounds: soundsEnabled,
          grid: {spacing: 16,
            length: 1,
            colour: '#2C344A',
            snap: false
          },
          zoom: {
            controls: true,
            wheel: true,
            startScale: 1.0,
            maxScale: 4,
            minScale: 0.25,
            scaleSpeed: 1.1
          },
          colours: {
            workspace: '#334771',
            flyout: '#283856',
            scrollbar: '#24324D',
            scrollbarHover: '#0C111A',
            insertionMarker: '#FFFFFF',
            insertionMarkerOpacity: 0.3,
            fieldShadow: 'rgba(255, 255, 255, 0.3)',
            dragShadowOpacity: 0.6
          }
        });

        // Restore previously displayed text.
        var text = sessionStorage.getItem('textarea');
        if (text) {
          document.getElementById('importExport').value = text;
        }
        taChange();

        // Restore event logging state.
        var state = sessionStorage.getItem('logEvents');
        logEvents(Boolean(state));

        // Restore flyout event logging state.
        state = sessionStorage.getItem('logFlyoutEvents');
        logFlyoutEvents(Boolean(state));
      }

      function toXml() {
        var output = document.getElementById('importExport');
        var xml = Blockly.Xml.workspaceToDom(workspace);
        output.value = Blockly.Xml.domToPrettyText(xml);
        output.focus();
        output.select();
        taChange();
      }

      function fromXml() {
        var input = document.getElementById('importExport');
        var xml = Blockly.Xml.textToDom(input.value);
        Blockly.Xml.domToWorkspace(workspace, xml);
        taChange();
      }

      function toCode(lang) {
        var output = document.getElementById('importExport');
        output.value = Blockly[lang].workspaceToCode(workspace);
        taChange();
      }

      // Disable the "Import from XML" button if the XML is invalid.
      // Preserve text between page reloads.
      function taChange() {
        var textarea = document.getElementById('importExport');
        sessionStorage.setItem('textarea', textarea.value)
        var valid = true;
        try {
          Blockly.Xml.textToDom(textarea.value);
        } catch (e) {
          valid = false;
        }
        document.getElementById('import').disabled = !valid;
      }

      function logEvents(state) {
        var checkbox = document.getElementById('logCheck');
        checkbox.checked = state;
        sessionStorage.setItem('logEvents', state ? 'checked' : '');
        if (state) {
          workspace.addChangeListener(logger);
        } else {
          workspace.removeChangeListener(logger);
        }
      }

      function logFlyoutEvents(state) {
        var checkbox = document.getElementById('logFlyoutCheck');
        checkbox.checked = state;
        sessionStorage.setItem('logFlyoutEvents', state ? 'checked' : '');
        if (state) {
          workspace.toolbox_.flyout_.workspace_.addChangeListener(logger);
        } else {
          workspace.toolbox_.flyout_.workspace_.removeChangeListener(logger);
        }
      }

      function logger(e) {
        console.log(e);
      }

      function glowBlock() {
        if (Blockly.selected) {
          workspace.glowBlock(Blockly.selected.id, true);
        }
      }

      function unglowBlock() {
        if (Blockly.selected) {
          workspace.glowBlock(Blockly.selected.id, false);
        }
      }

      function glowStack() {
        if (Blockly.selected) {
          workspace.glowStack(Blockly.selected.id, true);
        }
      }

      function unglowStack() {
        if (Blockly.selected) {
          workspace.glowStack(Blockly.selected.id, false);
        }
      }

      function sprinkles(n) {
        var prototypes = [];
        var toolbox = document.getElementById('toolbox');
        var blocks = toolbox.getElementsByTagName('block');
        for (var i = 0, block; block = blocks[i]; i++) {
          prototypes.push(block.getAttribute('type'));
        }
        for (var i = 0; i < n; i++) {
          var prototype = prototypes[Math.floor(Math.random() * prototypes.length)];
          var block = workspace.newBlock(prototype);
          block.initSvg();
          block.getSvgRoot().setAttribute('transform', 'translate(' +
          Math.round(Math.random() * 450 + 40) + ', ' +
          Math.round(Math.random() * 600 + 40) + ')');
          block.render();
        }
      }

      function spaghetti(n) {
        var xml = spaghettiXml;
        for(var i = 0; i < n; i++) {
          xml = xml.replace(/(<(statement|next)( name="SUBSTACK")?>)<\//g,
          '$1' + spaghettiXml + '</');
        }
        xml = '<xml xmlns="http://www.w3.org/1999/xhtml">' + xml + '</xml>';
        debugger;
        var dom = Blockly.Xml.textToDom(xml);
        console.time('Spaghetti domToWorkspace');
        Blockly.Xml.domToWorkspace(workspace, dom);
        console.timeEnd('Spaghetti domToWorkspace');
      }

      var spaghettiXml = [
        '  <block type="control_repeat">',
        '    <value name="TIMES">',
        '      <shadow type="math_whole_number">',
        '        <field name="NUM">10</field>',
        '      </shadow>',
        '    </value>',
        '    <statement name="SUBSTACK"></statement>',
        '    <next></next>',
        '  </block>'
      ].join('\n');

      function setSoundsEnabled(state) {
        var checkbox = document.getElementById('soundsEnabled');
        checkbox.checked = (state) ? 'checked' : '';
        sessionStorage.setItem('soundsEnabled', state);
      }
    </script>

    <style>
      html, body {
        height: 100%;
      }

      body {
        background-color: #fff;
        font-family: sans-serif;
        overflow: hidden;
      }

      h1 {
        font-weight: normal;
        font-size: 140%;
      }

      #blocklyDiv {
        float: right;
        height: 95%;
        width: 70%;
      }

      #collaborators {
        float: right;
        width: 30px;
        margin-left: 10px;
      }

      #collaborators > img {
        margin-right: 5px;
        height: 30px;
        padding-bottom: 5px;
        width: 30px;
        border-radius: 3px;
      }

      #importExport {
        font-family: monospace;
      }
    </style>
  </head>

  <body onload="start()">
    <div id="collaborators"></div>
    <div id="blocklyDiv"></div>

    <!-- Toolbox -->
    <xml id="toolbox" style="display: none">
      <category name="Events">
        <block type="event_whenflagclicked"></block>
        <block type="event_whenbroadcastreceived">
          <value name="CHOICE">
            <shadow type="dropdown_whenbroadcast">
              <field name="CHOICE">blue</field>
            </shadow>
          </value>
        </block>
        <block type="event_broadcast">
          <value name="CHOICE">
            <shadow type="dropdown_broadcast">
              <field name="CHOICE">blue</field>
            </shadow>
          </value>
        </block>
      </category>

      <category name="Control">
        <block type="control_forever"></block>
        <block type="control_repeat">
          <value name="TIMES">
            <shadow type="math_whole_number">
              <field name="NUM">4</field>
            </shadow>
          </value>
        </block>
        <block type="control_stop"></block>
        <block type="control_wait">
          <value name="DURATION">
            <shadow type="math_positive_number">
              <field name="NUM">1</field>
            </shadow>
          </value>
        </block>
      </category>

      <category name="Wedo">
          <block type="wedo_setcolor">
            <value name="CHOICE">
              <shadow type="dropdown_wedo_setcolor">
                <field name="CHOICE">mystery</field>
              </shadow>
            </value>
          </block>
          <block type="wedo_motorclockwise">
              <value name="DURATION">
                <shadow type="math_positive_number">
                  <field name="NUM">1</field>
                </shadow>
              </value>
          </block>
          <block type="wedo_motorcounterclockwise">
              <value name="DURATION">
                <shadow type="math_positive_number">
                  <field name="NUM">1</field>
                </shadow>
              </value>
          </block>
          <block type="wedo_motorspeed">
            <value name="CHOICE">
              <shadow type="dropdown_wedo_motorspeed">
                <field name="CHOICE">fast</field>
              </shadow>
            </value>
          </block>
          <block type="wedo_whentilt">
            <value name="CHOICE">
              <shadow type="dropdown_wedo_whentilt">
                <field name="CHOICE">forward</field>
              </shadow>
            </value>
          </block>
          <block type="wedo_whendistanceclose"></block>
      </category>
    </xml>

    <!-- Sidebar -->
    <h1>Horizontal Blocks</h1>
    <p>
      <a href="javascript:void(workspace.setVisible(true))">Show</a>
      - <a href="javascript:void(workspace.setVisible(false))">Hide</a>
    </p>

    <script>
      if (rtl) {
        document.write('[ &larr; RTL. Switch to <A HREF="?ltr">LTR</A>. ]');
      } else {
        document.write('[ &rarr; LTR. Switch to <A HREF="?rtl">RTL</A>. ]');
      }
    </script>

    <p>
      <input type="button" value="Export to XML" onclick="toXml()">
      &nbsp;
      <input type="button" value="Import from XML" onclick="fromXml()" id="import">
      <br>
      <textarea id="importExport" style="width: 26%; height: 12em"
        onchange="taChange();" onkeyup="taChange()"></textarea>
    </p>

    <p>
      Log events: &nbsp;
      <input type="checkbox" onclick="logEvents(this.checked)" id="logCheck">
    </p>

    <p>
      Log flyout events: &nbsp;
      <input type="checkbox" onclick="logFlyoutEvents(this.checked)" id="logFlyoutCheck">
    </p>

    <p>
      Enable sounds (after refresh): &nbsp;
      <input type="checkbox" onclick="setSoundsEnabled(this.checked)" id="soundsEnabled">
    </p>

    <p>
      Stress test: &nbsp;
      <input type="button" value="Sprinkles!" onclick="sprinkles(100)">
      <input type="button" value="Spaghetti!" onclick="spaghetti(10)">
    </p>

    <p>
      Glows: &nbsp;
      <input type="button" value="Glow last clicked block" onclick="glowBlock()" />
      <input type="button" value="Unglow last clicked block" onclick="unglowBlock()" />
      <input type="button" value="Stack glow last clicked block" onclick="glowStack()" />
      <input type="button" value="Stack unglow last clicked block" onclick="unglowStack()" />
    </p>

    <p>
      <input type="button" value="Undo" onclick="workspace.undo()" />
      <input type="button" value="Redo" onclick="workspace.undo(true)" />
    </p>
  </body>
</html>
